package com.tc.ssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Auther: tianchao
 * @Date: 2021/11/9 16:21
 * @Description:
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("my_sso_token") String ssoTokenValue){
        String s = stringRedisTemplate.opsForValue().get(ssoTokenValue);
        log.info("获取用户信息", s);
        return s;
    }

    /**
     * 登录页面
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirectUrl, Model model,
        @CookieValue(value = "my_sso_token",required = false) String ssoToken
        ){
        if (!StringUtils.isEmpty(ssoToken)){
            //说明之前有了登录痕迹
            String s = stringRedisTemplate.opsForValue().get(ssoToken);
            log.info("登录过了 并且登录信息是 {}", s);
            return "redirect:"+redirectUrl + "?token=" + ssoToken;
        }
        log.info("登录成功返回的地址：{}", redirectUrl);
        model.addAttribute("redirect_url", redirectUrl);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(
            @RequestParam("username") String username,
            @RequestParam("password")String password,
            @RequestParam("redirect_url")String redirectUrl,
            HttpServletResponse response
    ){
        log.info("处理登录 username: {},password: {}, redirectUrl:{}",username,password,redirectUrl);
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            stringRedisTemplate.opsForValue().set(uuid,username);
            response.addCookie(new Cookie("my_sso_token", uuid));
            return "redirect:"+redirectUrl + "?token=" + uuid;
        }
        //登录成功跳转 跳转到之前的页面
        return "";
    }
}
